import sys
import os
from pathlib import Path
import json

from selenium import webdriver
from selenium.common.exceptions import NoSuchWindowException
from urllib.parse import urlparse, urlencode
from pathlib import Path
from lly.server import generate_vim_url
from lly.logconfig import logger
from lly.brower import driver_path


class WebBrower:
    driver = None

    def openUrl(self, url, parms=''):
        targetUrl = urlparse(url)
        logger.info(f":WebBrower url {url} {parms}")
        if targetUrl.scheme  == 'http' or targetUrl.scheme == 'https':
            targetUrl = url
        else:
            if(url.startswith('~')):
                targetUrl = Path(url).expanduser()
            else:
                targetUrl = Path(url).resolve()
            targetUrl = generate_vim_url(targetUrl)

        if self.driver is None:
            self.driver = webdriver.Chrome(driver_path)
        is_empty = parms == '' or parms is None
        if not is_empty:
            targetUrl = targetUrl+'?'+urlencode(json.loads(parms))
        try:
            logger.info(targetUrl)
            self.driver.get(targetUrl)
        except Exception as e:
            print(f'{e}')
            self.driver = None
            #  self.openUrl(url, parms=parms)

    def close(self):
        if self.driver is not None:
            try:
                self.driver.close()
            finally:
                self.driver = None


webBrower = WebBrower()
if __name__ == '__main__':
    path = webdriver.Chrome(driver_path).service.path
    print(path)
